import json

from PyQt6.QtCore import QJsonDocument, QObject, QUrl, QSettings
from PyQt6.QtNetwork import QNetworkAccessManager, QNetworkRequest


class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            instance = super().__call__(*args, **kwargs)
            cls._instances[cls] = instance
        return cls._instances[cls]


class HttpApi(metaclass=Singleton):
    LOGIN_URL = "http://om.jujiembs.com/api/auth/login"
    DEVICES_LIST_URL = "http://om.jujiembs.com/api/tenant/deviceInfos"
    BASE_TELEMETRY_URL = "http://om.jujiembs.com/api/plugins/telemetry/DEVICE/"

    def __init__(self):
        self.manage = QNetworkAccessManager()
        self.request = QNetworkRequest()
        self.request.setHeader(QNetworkRequest.KnownHeaders.ContentTypeHeader, "application/json")
        self.settings = QSettings("userInfo")
        # 回调数据
        self.callback = None

    # get请求
    def requestGet(self, url, params=None, callback=None):
        self.request.setUrl(QUrl(url))
        if self.settings.value("token") is not None:
            headerValue = self.settings.value("token")
            self.request.setRawHeader("X-Authorization".encode('utf-8'), headerValue.encode('utf-8'))
        reply = self.manage.get(self.request)
        self.callback = callback
        reply.finished.connect(self.reponse)

    # post请求
    def requestPost(self, url, data=None, callback=None):
        self.request.setUrl(QUrl(url))
        if self.settings.value("token") is not None:
            headerValue = self.settings.value("token")
            self.request.setRawHeader("X-Authorization".encode('utf-8'), headerValue.encode('utf-8'))
        jsonData = None
        if data is not None:
            jsonData = QJsonDocument(data).toJson()
        reply = self.manage.post(self.request, jsonData)
        self.callback = callback
        reply.finished.connect(self.reponse)

    # 收到数据返回
    def reponse(self):
        reply = QObject.sender(QObject())
        data = reply.readAll()
        strdata = data.data().decode('utf-8')
        # 获取数据，字典类型
        if self.callback is not None:
            self.callback(json.loads(strdata))
        # 关闭连接
        reply.close()
        # 释放资源
        reply.deleteLater()
